var SimpleDataHandler = {
	preview: function(type, code) {
		function doSome(data) {
			var tmpData = [];
			if (type == 'signValue') {
				tmpData.push(['单列值']);
				tmpData.push([data]);
			} else if (type == 'smartParam') {
				headName = '参数值';
				tmpData.push(['参数值']);
				tmpData.push([SimpleDataHandler.getSmartParamName(code, data)]);
			}
			data = tmpData.length == 0 ? data : tmpData;

			if (SimpleDataHandler.isChange) {
				$_doc.unbind('saveSmartDataCache');
				$_doc.bind('saveSmartDataCache', function() {
					$_doc.data(SimpleDataHandler.id, data);
				})
			}

			var previewId = "#previewTable";
			$(previewId + ' table').remove();
			jQuery.jsontotable(data, {
				id: previewId,
				header: true,
				excel: true
			});
			$(previewId + ' table').addClass('stripe');
		}
		var url;
		var sendData = {
			pageId: pageId,
			code: code
		};
		if (type == 'signValue') {
			url = 'simpleData/getSimpleData';
		} else if (type == 'table') {
			url = 'table/getTable'
		} else if (type == 'smartParam') {
			url = 'editor/useArgList/getSimpleParamByPageId';
			delete sendData.code;
		}

		function buildData() {
			ck.util.sendAjax({
				url: url,
				data: sendData
			}, doSome);
		}
		if (SimpleDataHandler.isChange) {
			buildData();
		} else {
			var data = $_doc.data(SimpleDataHandler.id);
			if (data) {
				doSome(data);
			} else {
				buildData();
			}
		}
	},
	getSmartParamName: function(code, simpleParams) {
		if (!simpleParams) {
			$.ajax({
				url: 'editor/useArgList/getSimpleParamByPageId?pageId=' + pageId,
				async: false
			}).done(function(data) {
				simpleParams = data;
			})
		}

		function sortByNameLen(first, second) {
			var fNameLen = first.name.length;
			var sNameLen = second.name.length;
			return fNameLen - sNameLen;
		}
		if(simpleParams){
			simpleParams.sort(sortByNameLen).reverse();
		}
		for (var i = 0; i < simpleParams.length; i++) {
			var useArg = simpleParams[i];
			var argName = '#' + useArg.name;
			// 找到关键字
			if (code.indexOf(argName) > -1) {
				var sysArr = code.split(argName);
				code = sysArr.join(useArg.val);
			}
		}
		return code;
	},
	showSmartParam: function(id, code) {
		code = SimpleDataHandler.getSmartParamName(code);
		SimpleDataHandler.showData(id, code);
	},
	execObjs: function(objs, data, exec) {
		for (var i = 0; i < objs.length; i++) {
			var obj = objs[i];
			var backType = obj.backtype;
			var id = obj.id;
			if (backType == 'table') {
				var dataPoints = obj.datapoints;
				exec(id, dataPoints, data);
			} else {
				exec(id, data);
			}
		}
	},
	error: function() {
		var deCode = this.deCode;
		var codeObjsMap = $_doc.data('codeObjsMap');
		var objs = codeObjsMap[deCode];

		SimpleDataHandler.execObjs(objs, '脚本错误', SimpleDataHandler.showData);
		delete codeObjsMap[deCode];
	},
	showData: function(id, data) {
		var target = $('#' + id, CKEDITOR.instances.editor.document.$);
		target.text(data);
	},
	signValueDoSome: function(data) {
		var deCode = this.deCode;

		var codeObjsMap = $_doc.data('codeObjsMap');
		var objs = codeObjsMap[deCode];
		SimpleDataHandler.execObjs(objs, data, SimpleDataHandler.showData);
		delete codeObjsMap[deCode];
	},
	tableDoSome: function(data) {
		var deCode = this.deCode;

		var codeObjsMap = $_doc.data('codeObjsMap');
		var objs = codeObjsMap[deCode];

		function inner(id, dataPoints, data) {
			var previewId = "#expressionDiv";
			$(previewId + ' table').remove();
			jQuery.jsontotable(data, {
				id: previewId,
				header: true,
				excel: true
			});
			var inputObj = document.querySelector('#expressionDiv');
			var rules = new ruleJS('expressionDiv');
			rules.init();
			var parsed = rules.parse(dataPoints, inputObj);
			var error = parsed.error;
			var result = error ? '-' : parsed.result;
			SimpleDataHandler.showData(id, result);

			// 将table类型的数据缓存起来
			$_doc.data(id, data);
		}
		SimpleDataHandler.execObjs(objs, data, inner);

		delete codeObjsMap[deCode];
	},
	simpleDataLoadEvent: function(event) {
		var url, doSuccess;
		var attr = event.data,
			backType = attr.backtype,
			code = attr.code,
			id = attr.id,
			dataPoints = attr.datapoints;
		var context = {
			deCode: encodeURIComponent(code)
		};
		var error = SimpleDataHandler.error;
		if (backType == 'signValue') {
			doSuccess = SimpleDataHandler.signValueDoSome;
			url = 'simpleData/getSimpleData';
		} else if (backType == 'table') {
			doSuccess = SimpleDataHandler.tableDoSome;
			url = 'table/getTable';
		} else if (backType == 'smartParam') {
			SimpleDataHandler.showSmartParam(id, code);
			return;
		}
		ck.util.sendAjax({
			url: url,
			data: {
				pageId: pageId,
				code: code
			},
			context: context
		}, doSuccess, error);
	}
}

CKEDITOR.plugins.add('simpledata', {
	icons: 'simpledata',
	requires: 'widget',
	init: function(editor) {
		CKEDITOR.dialog.add('simpledata', this.path + 'dialogs/simpledata.js');

		editor.widgets.add('simpledata', {
			button: '插入数据',
			dialog: 'simpledata',
			requiredContent: 'span(h-card)',
			template: '<span class="h-card"></span>',
			init: function() {
				this.once('ready', function() {
					if (this.data.isLoad == 1) {
						// 设置为0，避免 ctrl+z 会再次执行
						this.setData('isLoad', 0);

						var code = this.element.getAttribute('code');
						var backType = this.element.getAttribute('backtype');
						var dataPoints = this.element.getAttribute('datapoints');
						var id = this.element.getAttribute('id');
						var attr = {
							code: code,
							backtype: backType,
							datapoints: dataPoints,
							id: id
						}

						var deCode = encodeURIComponent(code);

						if (backType == 'smartParam') {
							$_doc.bind('simpleDataLoadEvent', attr, SimpleDataHandler.simpleDataLoadEvent);
						} else {
							var codeObjsMap = $_doc.data('codeObjsMap') || {};
							var objs = codeObjsMap[deCode];
							if (objs) { // 已存在
								objs.push(attr);
								codeObjsMap[deCode] = objs;
							} else { // 未存在
								objs = [];
								objs.push(attr);
								codeObjsMap[deCode] = objs;

								$_doc.bind('simpleDataLoadEvent', attr, SimpleDataHandler.simpleDataLoadEvent);
							}
							$_doc.data('codeObjsMap', codeObjsMap);
						}
					}
				})
			},
			upcast: function(el, data) {
				if (el.name == 'span' && el.hasClass("h-card")) {
					// 标记此元素为页面加载的元素
					data.isLoad = 1;
					return el;
				}
			}
		});
	}
});